package scope;

import domain.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

/**
 * @author jackcfan
 * @date 2021/9/25
 */
public class ThreadLocalScopeTest {

    @Bean
    @Scope(ThreadLocalScope.SCOPE_NAME)
    User user(){
        User user = new User();
        user.setId(System.currentTimeMillis());
        return user;
    }

    public static void main(String[] args) throws InterruptedException {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(ThreadLocalScopeTest.class);

        applicationContext.addBeanFactoryPostProcessor(beanFactory -> {
            // 注册自定义 scope
            beanFactory.registerScope(ThreadLocalScope.SCOPE_NAME, new ThreadLocalScope());
        });

        applicationContext.refresh();

        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread(() -> {
                /**
                 * 同一个线程内获得的对象是相同的
                 * 不同线程获得的对象不同
                 * */
                User user = applicationContext.getBean("user", User.class);
                System.out.printf("[Thread id :%d] user = %s%n", Thread.currentThread().getId(), user);

                User user1 = applicationContext.getBean("user", User.class);
                System.out.println("user == user1 ? "+(user == user1));
            });
            thread.start();
            thread.join();
        }
        
        applicationContext.close();
    }
}
